//
//  LPUtils.m
//  LiePin
//
//  Created by apple on 13-12-5.
//  Copyright (c) 2013年 apple. All rights reserved.
//

#import "LPUtils.h"
#import "MBProgressHUD.h"
#import "Config.h"
#import "SVProgressHUD.h"
#import "Reachability.h"

#import <CommonCrypto/CommonDigest.h>

@implementation LPUtils

#pragma mark -UILabel参数设定
+ (void)initWihtLabel:(UILabel *)label color:(UIColor *)color fontSize:(float)size line:(int)line alignment:(NSTextAlignment)alignment
{
    label.backgroundColor = [UIColor clearColor];
    label.textAlignment = alignment;
    label.textColor = color;
    label.numberOfLines = line;
    [label setFont:[UIFont systemFontOfSize:size]];
}

#pragma mark -设置UITextField属性
+ (void)initWithTextField:(UITextField *)textField placeholder:(NSString *)placeholder textAlignment:(NSTextAlignment) textAlignment fontSzie:(float)fontSize textColor:(UIColor *)color
{
    textField.textColor = color;
    [textField setFont:[UIFont systemFontOfSize:fontSize]];
    textField.backgroundColor = [UIColor clearColor];
    textField.placeholder = placeholder;
    textField.returnKeyType = UIReturnKeyDone;
    textField.textAlignment = textAlignment;
}

+ (void) setButtonStyle:(UIButton *)button {
    [button.layer setMasksToBounds:YES];
    [button.layer setCornerRadius:5.0]; //设置矩形四个圆角半径
    [button.layer setBorderWidth:1.0]; //边框宽度
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGColorRef colorref = CGColorCreate(colorSpace,(CGFloat[]){ 0.77, 0.77, 0.77, 1 });
    [button.layer setBorderColor:colorref];//边框颜色
}

#pragma mark UIAlert
UIAlertView *codeAlert;
+ (void)addAlert:(NSString*)alertTitle AlertMessage:(NSString*)alertMessage
{
    if (!codeAlert.visible) {
        codeAlert = [[UIAlertView alloc]initWithTitle:alertTitle message:alertMessage delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [codeAlert show];
    }
}

#pragma mark - 字符串UTF-8编码
+ (NSString*) getEncodingWithUTF8 : (NSString*) str
{
    NSString *tempStr = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    return tempStr;
}

#pragma mark - 验证邮箱是否正确的方法 ^[A-Za-z0-9\u4E00-\u9FA5_-]+$
+(BOOL)isValidateEmail:(NSString *)email
{
    if(email.length==0)
        return NO;
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    BOOL isYES = [emailTest evaluateWithObject:email];
    return isYES;
}

#pragma mark - 判断有没有特殊字符
+(BOOL)isValidateSpecialCode:(NSString *)str
{
    if(str.length==0) {
        return NO;
    }
    
    NSString *emailRegex = @"^[A-Za-z]+$";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    BOOL isYES = [emailTest evaluateWithObject:str];
    return isYES;
}

+(BOOL)isValidatePhone:(NSString *)phone
{
    if (phone.length==0) {
        return NO;
    }
    NSString *phoneRegex = @"^1[3|4|5|7|8][0-9]\\d{8}$";
    NSPredicate *phonelTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
    BOOL isYES = [phonelTest evaluateWithObject:phone];
    return isYES;
}

+(BOOL)isValidateNumber:(NSString *)number{
    NSString *numberRegex = @"^[+-]?(0|([0-9]\\d*))(\\.\\d+)?%?$";;
    NSPredicate *numberTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", numberRegex];
    BOOL isYES = [numberTest evaluateWithObject:number];
    return isYES;
}

/**
 将字符串转换为MD5码
 @param str 字符串
 @returns 已转码为MD5的字符串
 */
+(NSString*)CCSMD5:(NSString*)str
{
    const char *cStr = [str UTF8String];
    unsigned char result[32];
    
    CC_MD5( cStr, strlen(cStr), result );
    
    return [[NSString
             stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
             result[0], result[1],
             result[2], result[3],
             result[4], result[5],
             result[6], result[7],
             result[8], result[9],
             result[10], result[11],
             result[12], result[13],
             result[14], result[15]
             ] lowercaseString];
}
#pragma mark - 格式化日期
+ (NSString*)formatDate:(NSDate *)date withFormat:(NSString *)format;
{
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = format;
    return [formatter stringFromDate:date];
}

+ (NSString *)getCurrentTime {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateTime = [formatter stringFromDate:[NSDate date]];
    return dateTime;
}

+ (NSString *) NSDateToNSString:(NSDate *)date
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyyMMdd_HHmmss"];
    NSString *strDate = [dateFormatter stringFromDate:date];
    return strDate;
}

/**
 * 计算指定时间与当前的时间差
 * @param compareDate   某一指定时间
 * @return 多少(秒or分or天or月or年)+前 (比如，3天前、10分钟前)
 */

+(NSString *) compareCurrentTime:(NSDate*) compareDate {
    
    NSTimeInterval  timeInterval = [compareDate timeIntervalSinceNow];
    timeInterval = -timeInterval;
    long temp = 0;
    NSString *result;
    if (timeInterval < 60) {
        result = [NSString stringWithFormat:@"刚刚"];
    } else if((temp = timeInterval/60) <60){
        result = [NSString stringWithFormat:@"%ld分前",temp];
    } else if((temp = temp/60) <24){
        result = [NSString stringWithFormat:@"%ld小时前",temp];
    } else if((temp = temp/24) <30){
        result = [NSString stringWithFormat:@"%ld天前",temp];
    } else if((temp = temp/30) <12){
        result = [NSString stringWithFormat:@"%ld月前",temp];
    } else{
        temp = temp/12;
        result = [NSString stringWithFormat:@"%ld年前",temp];
    }
    
    return  result;
}

+ (void)clearCache{

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES);
    NSString * _EGOCacheDirectory = [[[paths lastObject] stringByAppendingPathComponent:[[NSProcessInfo processInfo] processName]] stringByAppendingPathComponent:@"EGOCache"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray* array = [fileManager contentsOfDirectoryAtPath:_EGOCacheDirectory error:nil];
    for (int j=0; j<[array count]; j++) {
        
        NSString *itemPath = [[paths lastObject] stringByAppendingPathComponent:array[j]];
        [fileManager removeItemAtPath:itemPath error:nil];
    }
}

#pragma mark - 显示提示框 
MBProgressHUD *hud;
+(void)showTip:(NSString *)text inView:(UIView *)view{
//    if (hud) {
//        [hud hide:YES];
//        [hud removeFromSuperview];
//        hud = nil;
//    }
//    hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
//    hud.mode = MBProgressHUDModeCustomView;
//    hud.animationType = MBProgressHUDAnimationZoom;
//    hud.labelText = text;
//    hud.yOffset = -50;
//    hud.frameHeight = [self getStringHight:text font:hud.labelFont width:300];
//    hud.removeFromSuperViewOnHide = YES;
//    [hud hide:YES afterDelay:1.2];
    
}


//#pragma mark - 显示提示框
//SVProgressHUD *hud;
//+(void)showTip:(NSString *)text inView:(UIView *)view{
//    if (hud) {
//        [SVProgressHUD dismiss];
//        [hud removeFromSuperview];
//        hud = nil;
//    }
//    
//    [SVProgressHUD setBackgroundColor:[UIColor colorWithWhite:0.3 alpha:0.9]];
//    [SVProgressHUD setRingThickness:8.0];
//    [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
//    [SVProgressHUD show];
//    [SVProgressHUD setStatus:text];
//    [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"  当前为最新版本  "];
//    
////    hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
////    hud.mode = MBProgressHUDModeText;
////    hud.animationType = MBProgressHUDAnimationZoom;
////    hud.labelText = text;
////    hud.yOffset = -96;
////    hud.frameHeight = [self getStringHight:text font:hud.labelFont width:300];
////    hud.removeFromSuperViewOnHide = YES;
//    [hud hide:YES afterDelay:1.2];
//    
//}

+(void)saveData:(id)value forKey:(NSString *)key{
    [[NSUserDefaults standardUserDefaults] setObject:value forKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

+(NSString *)getForKey:(NSString *)key{
    
    return [[NSUserDefaults standardUserDefaults] objectForKey:key];
}

+(NSDictionary *)getPlistData:(NSString *)name{
    NSString *path = [LPUtils documentPath:name];
    BOOL exsit = [[NSFileManager defaultManager] fileExistsAtPath:path];
    if (!exsit) {
        path = [[NSBundle mainBundle] pathForResource:name ofType:@"plist"];
    }
    return [NSDictionary dictionaryWithContentsOfFile:path];
}
+(void)removeForKey:(NSString *)key{
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

+(CGFloat)getStringHight:(NSString*)input font:(UIFont*)font width:(CGFloat)width
{
    if (input == nil || font == nil || width <= 0) {
        return 0.0f;
    }
    
    CGSize s = CGSizeMake(width, CGFLOAT_MAX);
	CGSize size = [input sizeWithFont:font
                    constrainedToSize:s
                        lineBreakMode:NSLineBreakByWordWrapping];
    int height = size.height;
//    if (isIOS7) {
        height +=10;
//    }
	return height;
}

+(CGFloat)getStringWidth:(NSString*)input font:(UIFont*)font
{
    if (input == nil || font == nil ) {
        return 0.0f;
    }
    CGSize size = [input sizeWithFont:font
                          constrainedToSize:CGSizeMake(CGFLOAT_MAX, 0.0)
                              lineBreakMode:NSLineBreakByWordWrapping];

    int width = size.width;
    width += 5;
    return width;
}


+(NSString *)getVersion{
    return  [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
}

+(NSString *)getBundle{
    return  [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
}


+(NSString *)documentPath:(NSString *)name{
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES);
    NSString *plistPath1 = [paths objectAtIndex:0];
    return [plistPath1 stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",name]];
}
//+(BOOL)isValidateNumber:(NSString *)number{
//    NSString *numberRegex = @"^[+-]?(0|([1-9]\\d*))(\\.\\d+)?%?$";;
//    NSPredicate *numberTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", numberRegex];
//    BOOL isYES = [numberTest evaluateWithObject:number];
//    return isYES;
//}

+ (int)getStringLenghth:(NSString*)str {
    
    int strlength = 0;
    char* p = (char*)[str cStringUsingEncoding:NSUnicodeStringEncoding];
    for (int i=0 ; i<[str lengthOfBytesUsingEncoding:NSUnicodeStringEncoding] ;i++) {
        if (*p) {
            p++;
            strlength++;
        }
        else {
            p++;
        }
    }
    return (strlength+1)/2;
    
}
+(UIView *)showPickerView:(id)delegate withTitle:(NSString *)title withAction:(SEL)action withTag:(NSInteger)tag{
    return nil;
//    
//    UIPickerView *pickerView;
//    CGRect bounds = [UIApplication sharedApplication].keyWindow.bounds;
//    UIView *bgView = [[UIView alloc] initWithFrame:bounds];
//    bgView.backgroundColor = [UIColor blackColor];
//    bgView.alpha = 0.4;
//    bgView.tag = 20000;
//    UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:delegate action:action];
//    [bgView addGestureRecognizer:tapGes];
//    
//    UIView *superView = [[UIView alloc] initWithFrame:CGRectMake(0,bounds.size.height, ScreenWidth, 260)];
//    superView.tag = 20001;
//    
//    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0,0, ScreenWidth, 44)];
//    titleView.backgroundColor = MColor(0, 0, 0, 1);
//    
//    UILabel *LabelTitel = [[UILabel alloc] initWithFrame:titleView.frame];
//    LabelTitel.text = title;
//    LabelTitel.font = [UIFont systemFontOfSize:12];
//    LabelTitel.textColor = [UIColor grayColor];
//    LabelTitel.textAlignment = NSTextAlignmentCenter;
//    LabelTitel.backgroundColor = [UIColor clearColor];
//    [titleView addSubview:LabelTitel];
//    
//    UIButton *btnCancle = [[UIButton alloc] initWithFrame:CGRectMake(16, 0, 40, 40)];
//    [btnCancle setTitle:@"取消" forState:UIControlStateNormal];
//    [btnCancle setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    btnCancle.tag = 2000;
//    [btnCancle addTarget:delegate action:action forControlEvents:UIControlEventTouchUpInside];
//    
//    
//    pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0,0,ScreenWidth,216)];
//    pickerView.delegate = delegate;
//    pickerView.tag = tag;
//    pickerView.backgroundColor = [UIColor whiteColor];
//    pickerView.dataSource = delegate;
//    pickerView.showsSelectionIndicator = YES;
//    
//    UIButton *btnOK = [[UIButton alloc] initWithFrame:CGRectMake(0, pickerView.frameBottom, ScreenWidth, 44)];
//    btnOK.tag = 2001;
//    [btnOK setImage:isIPhone6?[UIImage imageNamed:@"alertView_btnok_6"]:[UIImage imageNamed:@"alertView_btnok"] forState:UIControlStateNormal];
//    [btnOK setImage:isIPhone6?[UIImage imageNamed:@"alertView_btnok_light_6"]:[UIImage imageNamed:@"alertView_btnok_light"] forState:UIControlStateHighlighted];
//    [btnOK addTarget:delegate action:action forControlEvents:UIControlEventTouchUpInside];
//
////    [titleView addSubview:btnCancle];
//    
////    [superView addSubview:titleView];
//    [superView addSubview:pickerView];
//    superView.frameTop = bounds.size.height;
//    UIWindow *window = [[UIApplication sharedApplication].windows firstObject];
//    [window addSubview:bgView];
//    [window addSubview:superView];
//    [superView addSubview:btnOK];
//
//
//    return superView;
}



+(UIView *)showView:(id)delegate withTitle:(NSString *)title withTitleArray:(NSArray *)array withAction:(SEL)action withTag:(NSInteger)tag {
    
//    CGRect bounds = [UIApplication sharedApplication].keyWindow.bounds;
//    UIView *bgView = [[UIView alloc] initWithFrame:bounds];
//    bgView.backgroundColor = [UIColor blackColor];
//    bgView.alpha = 0.4;
//    bgView.tag = 20000;
//    UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:delegate action:action];
//    [bgView addGestureRecognizer:tapGes];
//    
//    UIView *superView = [[UIView alloc] initWithFrame:CGRectMake(0,bounds.size.height, ScreenWidth, 172)];
//    superView.backgroundColor = [UIColor whiteColor];
//    superView.tag = 20001;
//    
//    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
//    button1.frame = CGRectMake(0, superView.frameHeight-152, ScreenWidth, 44);
//    [button1 setTitle:array[0] forState:UIControlStateNormal];
//    [button1 setTitleColor:GrayColor forState:UIControlStateNormal];
//    [button1 setTitleColor:GreenColor forState:UIControlStateHighlighted];
//    button1.tag = 2004;
//    [button1 addTarget:delegate action:action forControlEvents:UIControlEventTouchUpInside];
//    button1.titleLabel.font = [UIFont systemFontOfSize:18];
//    
//    UIButton *button2 = [UIButton buttonWithType:UIButtonTypeCustom];
//    button2.frame = CGRectMake(0, button1.frameBottom+1, ScreenWidth, 44);
//    [button2 setTitle:array[1] forState:UIControlStateNormal];
//    [button2 setTitleColor:GrayColor forState:UIControlStateNormal];
//    [button2 setTitleColor:GreenColor forState:UIControlStateHighlighted];
//    button2.tag = 2005;
//    [button2 addTarget:delegate action:action forControlEvents:UIControlEventTouchUpInside];
//    button2.titleLabel.font = [UIFont systemFontOfSize:18];
//    
//    UIImage *img = [UIImage imageNamed:@"left_cellline"];
//    UIImageView *imv = [[UIImageView alloc] initWithFrame:CGRectMake(0, button1.frameBottom, ScreenWidth, 1)];
//    imv.image = img;
//    
//    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0,superView.frameHeight-192, ScreenWidth, 44)];
//    titleView.backgroundColor = [UIColor whiteColor];
//    
//    UILabel *LabelTitel = [[UILabel alloc] initWithFrame:titleView.frame];
//    LabelTitel.text = title;
//    LabelTitel.font = [UIFont systemFontOfSize:12];
//    LabelTitel.textColor = [UIColor grayColor];
//    LabelTitel.textAlignment = NSTextAlignmentCenter;
//    LabelTitel.backgroundColor = [UIColor clearColor];
//    [titleView addSubview:LabelTitel];
//    
//    UIButton *btnOK = [[UIButton alloc] initWithFrame:CGRectMake(0, superView.frameHeight-44, ScreenWidth, 44)];
//    btnOK.tag = 2001;
//    [btnOK setImage:isIPhone6?[UIImage imageNamed:@"alertView_btncancel_6"]:[UIImage imageNamed:@"alertView_btncancel"] forState:UIControlStateNormal];
//    [btnOK setImage:isIPhone6?[UIImage imageNamed:@"alertView_btncancel_light_6"]:[UIImage imageNamed:@"alertView_btncancel_light"] forState:UIControlStateHighlighted];
//    [btnOK addTarget:delegate action:action forControlEvents:UIControlEventTouchUpInside];
//    
//    superView.frameTop = bounds.size.height;
//    UIWindow *window = [[UIApplication sharedApplication].windows firstObject];
//    [window addSubview:bgView];
//    [window addSubview:superView];
//    [superView addSubview:btnOK];
//    [superView addSubview:imv];
//
////    [superView addSubview:titleView];
//    [superView addSubview:button1];
//    [superView addSubview:button2];

//    return superView;
    
    return nil;
}

+(UIView *)showDatePickerView:(id)delegate withTitle:(NSString *)title withAction:(SEL)action withTag:(NSInteger)tag{
//    
//    UIDatePicker *pickerView;
//    CGRect bounds = [UIApplication sharedApplication].keyWindow.bounds;
//    UIView *bgView = [[UIView alloc] initWithFrame:bounds];
//    bgView.backgroundColor = [UIColor blackColor];
//    bgView.alpha = 0.4;
//    bgView.tag = 20000;
//    
//    UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:delegate action:action];
//    [bgView addGestureRecognizer:tapGes];
//    
//    UIView *superView = [[UIView alloc] initWithFrame:CGRectMake(0,bounds.size.height, ScreenWidth, 260)];
//    superView.tag = 20001;
//    
//    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0,0, ScreenWidth, 40)];
//    titleView.backgroundColor = GreenColor;
//    
//    UILabel *LabelTitel = [[UILabel alloc] initWithFrame:titleView.frame];
//    LabelTitel.text = title;
//    LabelTitel.font = [UIFont systemFontOfSize:16];
//    LabelTitel.textColor = [UIColor whiteColor];
//    LabelTitel.textAlignment = NSTextAlignmentCenter;
//    LabelTitel.backgroundColor = [UIColor clearColor];
//    [titleView addSubview:LabelTitel];
//    
//    UIButton *btnCancle = [[UIButton alloc] initWithFrame:CGRectMake(16, 0, 40, 40)];
//    [btnCancle setTitle:@"取消" forState:UIControlStateNormal];
//    [btnCancle setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    btnCancle.tag = 2000;
//    [btnCancle addTarget:delegate action:action forControlEvents:UIControlEventTouchUpInside];
//    
//    UIButton *btnOK = [[UIButton alloc] initWithFrame:CGRectMake(200, 0, 40, 40)];
//    [btnOK setTitle:@"确定" forState:UIControlStateNormal];
//    btnOK.tag = 2001;
//    [btnOK setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    [btnOK addTarget:delegate action:action forControlEvents:UIControlEventTouchUpInside];
//    
//    pickerView = [[UIDatePicker alloc] initWithFrame:CGRectMake(0,titleView.frame.origin.y+40,320,220)];
//    pickerView.tag = tag;
//    pickerView.minimumDate = [NSDate date];
//    pickerView.datePickerMode = UIDatePickerModeDate;
//    pickerView.backgroundColor = [UIColor whiteColor];
//    
//    [titleView addSubview:btnCancle];
//    [titleView addSubview:btnOK];
//    
//    [superView addSubview:titleView];
//    [superView addSubview:pickerView];
//    superView.frameTop = bounds.size.height;
//    UIWindow *window = [UIApplication sharedApplication].keyWindow;
//    [window addSubview:bgView];
//    [window addSubview:superView];
//    
//    return superView;
    
    return nil;
}

+ (BOOL) IsEnableWIFI {
    return ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable);
}

// 是否3G
+ (BOOL) IsEnable3G {
    return ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable);
}

+ (BOOL)isNotEnableNet{
    return ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] == NotReachable);
}


+ (BOOL)checkEnableNet{
    if ([self isNotEnableNet]) {
        return NO;
    }
    return YES;
}

@end
